package com.lcg.word.ui

import android.annotation.SuppressLint
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Path
import android.text.Layout
import android.text.StaticLayout
import android.text.TextPaint
import android.view.MotionEvent
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.asComposePaint
import androidx.compose.ui.graphics.asComposePath
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.drawscope.drawIntoCanvas
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.input.pointer.pointerInteropFilter
import androidx.compose.ui.layout.onSizeChanged
import com.lcg.word.DigitalInkManager
import com.lcg.word.ui.theme.PurpleGrey80
import kotlin.math.min

/**
 * 自定义widget
 *
 * @author lei.chuguang Email:475825657@qq.com
 */
/**手写板*/
@SuppressLint("UnrememberedMutableState")
@Composable
@OptIn(ExperimentalComposeUiApi::class)
fun WritingBoard(resetFlag: Int) {
    //重置刷新
    if (resetFlag < 0) return
    val currentStroke = Path()
    val currentStrokePaint = Paint().apply {
        color = -0x104738
        isAntiAlias = true
        strokeWidth = 4f
        style = Paint.Style.STROKE
        strokeJoin = Paint.Join.ROUND
        strokeCap = Paint.Cap.ROUND
    }
    var canvasBitmap: Bitmap? = null
    var drawCanvas: Canvas? = null
    var update by mutableIntStateOf(0)
    // Canvas更新的时候，上部分代码不会被重复执行，所以无需remember
    Canvas(
        modifier = Modifier
            .fillMaxSize()
            .onSizeChanged {
                val width = it.width
                val height = it.height
                canvasBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
                drawCanvas = Canvas(canvasBitmap!!).apply {
                    val textPaint = TextPaint().apply {
                        textSize = min(width, height) / 4f
                        isAntiAlias = true
                        color = PurpleGrey80.toArgb() and 0x2FFFFFFF
                    }
                    save()
                    val layout =
                        StaticLayout.Builder
                            .obtain("手写区域", 0, 4, textPaint, width)
                            .setAlignment(Layout.Alignment.ALIGN_CENTER)
                            .build()
                    translate(0f, (height - layout.height) / 2f)
                    layout.draw(this)
                    restore()
                }
            }
            .pointerInteropFilter { event ->
                val action = event.actionMasked
                val x = event.x
                val y = event.y
                when (action) {
                    MotionEvent.ACTION_DOWN -> currentStroke.moveTo(x, y)
                    MotionEvent.ACTION_MOVE -> currentStroke.lineTo(x, y)
                    MotionEvent.ACTION_UP -> {
                        currentStroke.lineTo(x, y)
                        drawCanvas?.drawPath(currentStroke, currentStrokePaint)
                        currentStroke.reset()
                    }

                    else -> {
                    }
                }
                update++
                DigitalInkManager.addNewTouchEvent(event)
                true
            }
    ) {
        drawIntoCanvas {
            if (update >= 0) {
                it.drawImage(
                    canvasBitmap!!.asImageBitmap(),
                    Offset.Zero,
                    Paint().asComposePaint()
                )
                it.drawPath(currentStroke.asComposePath(), currentStrokePaint.asComposePaint())
            }
        }
    }
}